package com.han.hotelplat.service.childtask.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.han.hotelplat.pojo.childtask.Childtask;
import com.han.hotelplat.pojo.ctroomtype.CtRoomtype;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.hhm.HotelHmanager;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.hotelroom.HotelRoom;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.pojo.wallet.Wallet;
import com.han.hotelplat.service.bill.BillService;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.emtask.EmTaskService;
import com.han.hotelplat.service.hhm.HotelHmanagerService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;
import com.han.hotelplat.service.hotelroom.HotelRoomService;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.base.EntityManage;
import com.han.hotelplat.comm.utils.AppEmployyePushUtil;
import com.han.hotelplat.comm.utils.AppHotelPushUtil;
import com.han.hotelplat.comm.utils.DateUtil;
import com.han.hotelplat.comm.utils.LogUtil;
import com.han.hotelplat.comm.utils.MsgHelp;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.dao.childtask.ChildTaskDao;
import com.han.hotelplat.dao.employee.EmployeeDao;
import com.han.hotelplat.dao.emtask.EmtaskDao;
import com.han.hotelplat.dao.hotel.HotelDao;
import com.han.hotelplat.dao.task.TaskDao;
import com.han.hotelplat.dao.wallet.WalletDao;

@Service
public class ChildTaskServiceImpl implements ChildTaskService{
	@Autowired
	private ChildTaskDao childTaskDao;
	@Autowired
	private EntityManage entityManage;
	@Autowired
	private WalletDao walletDao;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private BillService billService;
	@Autowired
	private TaskDao taskDao;
	@Autowired
	private HotelDao hotelDao;
	@Autowired
	private EmTaskService emTaskService;
	@Autowired
	private HotelmanagerService hotelmanagerService;
	@Autowired
	private HotelHmanagerService hhmService;
	@Autowired
	private HotelRoomService hotelRoomService;
	
	@Override
	public List<Childtask> getTaskAttendance(String taskid, String date) {
		List<Childtask> li = childTaskDao.getTaskAttendance(taskid, date);
		for(Childtask ct : li){
			String sql2 = "SELECT roomtypeid, roomname, SUM(count) FROM tb_ct_roomtype "
					+ " WHERE taskid='"+taskid+"' AND creatdate='"+date+"' AND emid='"+ct.getEmid()+"'"
					+ " GROUP BY roomtypeid,roomname";
			List<Object> ctLi = entityManage.findBySql(sql2);
			JSONArray array = new JSONArray();
			for(int i= 0 ; i<ctLi.size(); i++){
				Map<String, Object> roomType = new HashMap<String, Object>();
				Object[] ory = (Object[]) ctLi.get(i);
				if(ory[0] != null){//房型ID
					roomType.put("id", ory[0].toString());
				}
				if(ory[1] != null){//房型名ID
					roomType.put("name", ory[1].toString());
				}
				if(ory[2] != null){//数量ID
					roomType.put("count", ory[2].toString());
				}
				array.add(roomType);
			}
			ct.setRoomdetail(array);
		}
		return li;
	}

	@Override
	public Map<String, Object> getEmTaskAttendance(String taskid, String userid, String date) {
		Map<String,Object> data = new HashMap<String, Object>();
		Employee em = employeeDao.findEmployeeByUerid(userid);
		List<Childtask> li = childTaskDao.getEmTaskAttendance(taskid,userid,date);
		data.put("childtaskList", li);
		Float sumroomcount = 0f;
		for(Childtask ct : li){
			String sql2 = "SELECT roomtypeid, roomname, SUM(count),creatdate FROM tb_ct_roomtype "
					+ " WHERE ctid='"+ct.getId()+"' AND emid='"+ct.getEmid()+"'"
					+ " GROUP BY roomtypeid,roomname, creatdate";
			List<Object> ctLi = entityManage.findBySql(sql2);
			JSONArray array = new JSONArray();
			for(int i= 0 ; i<ctLi.size(); i++){
				Map<String, Object> roomType = new HashMap<String, Object>();
				Object[] ory = (Object[]) ctLi.get(i);
				if(ory[0] != null){//房型ID
					roomType.put("id", ory[0].toString());
				}
				if(ory[1] != null){//房型名ID
					roomType.put("name", ory[1].toString());
				}
				if(ory[2] != null){//数量ID
					roomType.put("count", ory[2].toString());
				}
				if(ory[3] != null){//时间
					roomType.put("date", ory[3].toString());
				}
				array.add(roomType);
			}
			ct.setRoomdetail(array);
			sumroomcount = sumroomcount
					+ (ct.getRoomcount() == null ? 0 : ct.getRoomcount());
		}
		data.put("sumroomcount", sumroomcount);
		data.put("realname", em.getRealname());
		return data;
	}

	@Override
	public List<Childtask> getTaskRoomCountGroupByDate(String taskid, String emid) {
		List<Childtask> ctli = new ArrayList<Childtask>();
		String sql = "select sum(roomcount),creattime, result from tb_child_task "
				+ "where 1=1 and taskid= '"+taskid+"'";
		if(StringUtils.isNotBlank(emid)){
			sql = sql+" and emid='"+emid+"'";
		}
		sql = sql + "  group by result,creattime "
				+ "ORDER BY  creattime DESC";
		List<Object[]> re = entityManage.findBySql(sql);
		Map<String, Childtask> tmp = new LinkedHashMap<String, Childtask>();
		if(re.size() != 0){
			for(Object[] o : re){
				Object[] oarray = new Object[1];
				oarray = o;
				Childtask ct = new Childtask();
				if(oarray[0] == null){
					ct.setRoomcount(0f);
				}else{
					ct.setRoomcount(Float.parseFloat(oarray[0].toString()));
				}
				ct.setCreattime(DateUtil.parseYMD(oarray[1].toString()));
				ct.setResult(Integer.parseInt(oarray[2].toString()));
				
				Childtask tmpct = tmp.get(DateUtil.formatYMD(ct.getCreattime()));
				if(tmpct == null){
					tmpct = ct;
					tmp.put(DateUtil.formatYMD(ct.getCreattime()), tmpct);
				}else{
					tmpct.setRoomcount(tmpct.getRoomcount()+ct.getRoomcount());
					//有待确认考勤阶段
					if(ct.getResult().intValue() == Constant.ATTENDANCE_SUBMIMT
							|| tmpct.getResult().intValue() == Constant.ATTENDANCE_NO_SUBMIMT){
						tmpct.setResult(Constant.ATTENDANCE_SUBMIMT);
					}
					tmp.put(DateUtil.formatYMD(ct.getCreattime()), tmpct);
				}
			}
		}
		for (String key : tmp.keySet()) {
			Childtask tmpct = tmp.get(key);
			//有待确认考勤阶段
			if(tmpct.getResult().intValue() == Constant.ATTENDANCE_SUBMIMT){
				tmpct.setResult(Constant.ATTENDANCE_SUBMIMT);
			}else{
				tmpct.setResult(Constant.ATTENDANCE_HASAUTH);
			}
			String sql2 = "SELECT roomtypeid, roomname, SUM(count),creatdate FROM tb_ct_roomtype "
					+ " WHERE taskid='"+taskid+"' AND creatdate='"+key+"' ";
			if(StringUtils.isNotBlank(emid)){
				sql2 = sql2 + " and emid='"+emid+"'";
			}
			sql2 = sql2	+ " GROUP BY roomtypeid,roomname, creatdate";
			List<Object> ctLi = entityManage.findBySql(sql2);
			Childtask ct = tmp.get(key);
			JSONArray array = new JSONArray();
			for(int i= 0 ; i<ctLi.size(); i++){
				Map<String, Object> roomType = new HashMap<String, Object>();
				Object[] ory = (Object[]) ctLi.get(i);
				if(ory[0] != null){//房型ID
					roomType.put("id", ory[0].toString());
				}
				if(ory[1] != null){//房型名ID
					roomType.put("name", ory[1].toString());
				}
				if(ory[2] != null){//数量ID
					roomType.put("count", ory[2].toString());
				}
				if(ory[3] != null){//时间
					roomType.put("date", ory[3].toString());
				}
				array.add(roomType);
			}
			ct.setRoomdetail(array);
		}
		ctli.addAll(tmp.values());
		return ctli;
	}

	@Override
	public Map<String,Object> authTaskAttendance(String childtaskids, Integer hotelid) {
		Map<String,Object> data = new HashMap<String, Object>();
		Wallet wallet = walletDao.getMyWallet(hotelid.toString());
		if(wallet == null){
			data.put("code", -1);
			data.put("message", "酒店钱包没被创建");
		}
		
		JSONArray ctidsjarray = JSONArray.parseArray(childtaskids);
		String ctids = "-1";
		for(Object js : ctidsjarray){
			int id = JSONObject.parseObject(js.toString()).getIntValue("id");
			ctids =ctids +","+id;
		}
		
		
		float costmoney = 0f;
		float roomcount = 0f;
		String sql = "SELECT cr.roomtypeid, cr.roomname, SUM(count), cr.price FROM tb_ct_roomtype as cr, tb_child_task as ct "
				+ " WHERE  cr.ctid = ct.id and cr.ctid in("+ctids+") and ct.result in (1,2) "
				+ " GROUP BY cr.roomtypeid,cr.roomname,cr.price";
		List<Object> ctli = entityManage.findBySql(sql);
		JSONArray array = new JSONArray();
		for(int i= 0 ; i<ctli.size(); i++){
			float price = 0f;
			float count = 0f;
			Object[] ory = (Object[]) ctli.get(i);
			JSONObject js = new JSONObject();
			if(ory[1] != null){//房型名
				js.put("roomname", ory[1].toString());
			}
			if(ory[2] != null){//数量
				js.put("count", Float.parseFloat(ory[2].toString()));
				count = Float.parseFloat(ory[2].toString());
			}
			if(ory[3] != null){//单价
				js.put("price", Float.parseFloat(ory[3].toString()));
				price = Float.parseFloat(ory[3].toString());
			}
			roomcount += count;
			costmoney += count * price;
			array.add(js);
		}
		DecimalFormat   fnum  =   new  DecimalFormat("##0.00");  
		String count =fnum.format(roomcount);     
		data.put("roomcount", count);//总房量
		data.put("costmoney", costmoney);//总金额
		data.put("balance", wallet.getBalance());//酒店余额
		data.put("roomdetail", array);
		if( wallet.getBalance()<0){//授信余额
			data.put("overdraft", wallet.getOverdraft()+wallet.getBalance());
    	}else{
    		data.put("overdraft", wallet.getOverdraft());
		}
		if(costmoney > (wallet.getBalance()+wallet.getOverdraft())){//超过钱包额度
			data.put("code", -2);
			data.put("message", "钱包余额不足");
			return data;
		}
		
		data.put("code", 0);
		data.put("message", "钱包充足可以确认考勤");
		return data;
	}

	@Override
	public Map<String, Object> modifyChildTask(Childtask newChildtask) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Childtask> getTaskRoomCountGroupByEm(String taskid, String date) {
		List<Childtask> ctli = new ArrayList<Childtask>();
		String sql = "select sum(ct.roomcount),ct.emid,"
				+ "(SELECT realname FROM tb_employee WHERE userid=ct.emid),ct.result "
				+ " from tb_child_task AS ct, tb_employee AS em "
				+ " where ct.taskid= '"+taskid +"'";
		if(StringUtils.isNotBlank(date)){
			sql = sql +" and ct.creattime='"+date+"'";
		}
				
		sql = sql + " and em.userid=ct.emid  group by ct.result,em.userid ";
		List<Object[]> re = entityManage.findBySql(sql);
		Map<String, Childtask> tmp = new HashMap<String, Childtask>();
		if(re.size() != 0){
			for(Object[] o : re){
				Object[] oarray = new Object[1];
				oarray = o;
				Childtask ct = new Childtask();
				ct.setRoomcount(Float.parseFloat(oarray[0].toString()));
				ct.setEmid(oarray[1].toString());
				ct.setRealname(oarray[2].toString());
				ct.setResult(Integer.parseInt(oarray[3].toString()));
				Childtask tmpct = tmp.get(ct.getEmid().toString());
				
				if(tmpct == null){
					tmpct = ct;
				}else{
					tmpct.setRoomcount(tmpct.getRoomcount()+ct.getRoomcount());
					//处于待确认考勤阶段
					if(ct.getResult().intValue() == Constant.ATTENDANCE_SUBMIMT){
						tmpct.setResult(Constant.ATTENDANCE_SUBMIMT);
					}
				}
				tmp.put(ct.getEmid().toString(), tmpct);
			}
			for(String emid : tmp.keySet()){
				String sql2 = "SELECT roomtypeid, roomname, SUM(count) FROM tb_ct_roomtype "
						+ " WHERE taskid='"+taskid+"' AND emid='"+emid+"'";
				
				if(StringUtils.isNotBlank(date)){
					sql2 = sql2 +" and creatdate='"+date+"'";
				}
				sql2 = sql2	+ " GROUP BY roomtypeid,roomname";
				List<Object> ctLi = entityManage.findBySql(sql2);
				JSONArray array = new JSONArray();
				float sumcount = 0f;
				for(int i= 0 ; i<ctLi.size(); i++){
					Map<String, Object> roomType = new HashMap<String, Object>();
					Object[] ory = (Object[]) ctLi.get(i);
					if(ory[0] != null){//房型ID
						roomType.put("id", ory[0].toString());
					}
					if(ory[1] != null){//房型名ID
						roomType.put("name", ory[1].toString());
					}
					if(ory[2] != null){//数量ID
						roomType.put("count", Float.parseFloat(ory[2].toString()));
						sumcount +=  Float.parseFloat(ory[2].toString());
					}else{
						roomType.put("count", 0);
					}
					array.add(roomType);
				}
				Childtask ct = tmp.get(emid);
				ct.setRoomcount(sumcount);
				ct.setRoomdetail(array);
			}
		}
		ctli.addAll(tmp.values());
		return ctli;
	}

	/**
	 * 确认考勤并支付
	 */
	@Override
	public Map<String, Object> paymentChildTask(String childtaskids,
			Integer hotelid, String userId, String realName) {
		Map<String,Object> data = new HashMap<String, Object>();
		Wallet expwallet = walletDao.getMyWallet(hotelid.toString());
		Wallet inwallet = walletDao.getMyWallet(Constant.WALLET_ID.toString());
		if(expwallet == null){
			data.put("code", -1);
			data.put("message", "酒店钱包没被创建");
		}
		JSONArray ctidsjarray = JSONArray.parseArray(childtaskids);
		String ctids = "-1";
		for(Object js : ctidsjarray){
			int id = JSONObject.parseObject(js.toString()).getIntValue("id");
			ctids =ctids +","+id;
		}
		String hql = "from Childtask where result in (1,2) and id in("+ctids+")";//排除已确认过的
		List<Childtask> ctli = childTaskDao.findByHQL(hql);
		float costmoney = 0;
		String taskid = "";
		for(Childtask ct : ctli){
			costmoney = costmoney+ct.getCostmoney();
			taskid = ct.getTaskid();
		}
		Task task = taskDao.findTaskByTaskid(taskid);
		Hotel h = hotelDao.findById(task.getHotelid());
		if((expwallet.getBalance().floatValue()+expwallet.getOverdraft().floatValue())<costmoney){
			data.put("code", -2);
			data.put("message", "余额不足，不能支付");
			return data;
		}
		for(Childtask ct : ctli){
			String remark = "任务交易，任务id="+ct.getTaskid();
			billService.creatBill(expwallet.getId(), inwallet.getId(), ct.getCostmoney(), 
					Constant.BILL_TYPE_TASK, remark, 
					ct.getTaskid(), ct.getId(), Constant.CHARGE_CHANNEL_TRANSFER,realName);
			ct.setResult(Constant.ATTENDANCE_HASAUTH);//状态修改为已确认
			ct.setAuditor(userId);
			childTaskDao.update(ct);
			Employee em = employeeDao.findEmployeeByUerid(ct.getEmid());
			if(!StrUtil.isNullOrEmpty(em.getPushkey())){
				JSONObject reqparam = new JSONObject();
				reqparam.put("taskId", taskid);
				AppEmployyePushUtil.pushMessage(em.getPushkey(), 
						"【有人有活】", em.getRealname()+"您好，"+h.getHotelname()
						+"已确认您的今日房量，请登录【有人有活App】查看详情", "pageOrderDetail", reqparam);
			}
		}
		
		List<Childtask> all = childTaskDao.getAllEmTaskAttendance(taskid, null);
		List<Childtask> availability = childTaskDao.getAllEmTaskAttendance(taskid, null);
		
		for(Childtask ct : all){
			if(ct.getRoomcount() != null && ct.getRoomcount().intValue() >= 0){//有提交考勤
				availability.add(ct);
			}
		}
		List<Childtask> li = childTaskDao.getAllEmTaskAttendance(taskid, 3);//查询已确认支付的考勤
		if(availability.size() == li.size()){//全部确认了
			//任务进行到了最后一天
			if(DateUtil.daysDistance(new Date(),task.getEndtime()) == 0){
				LogUtil.info("任务已经到最后一天了修改状态为已服务："+task.getTaskid());
				task.setState(Constant.TASK_STATE_HASSERVICE);//状态修改为已服务
				taskDao.update(task);
			}
		}
		
		data.put("code", 0);
		data.put("message", "支付成功");
		return data;
	}

	@Override
	public void save(Childtask ct) {
		childTaskDao.save(ct);
	}

	@Override
	public Map<String, Object> submitTaskAttendance(String taskid, String date,
			String userid, Float roomcount, String roomDetail) {
		Map<String, Object> re = getEmTaskAttendance(taskid, userid,null);
		List<Childtask> ctli = (List<Childtask>) re.get("childtaskList");
		String emName = (String) re.get("realname");
		re.clear();
		Task t = taskDao.findTaskByTaskid(taskid);
		if(t.getState().intValue() == Constant.TASK_STATE_STOP){
			re.put("code", -2);
			re.put("message", "任务已经停止不能继续提交考勤了");
			return re;
		}
		if(System.currentTimeMillis() > (t.getEndtime().getTime()+23*DateUtil.HOUR)){
			re.put("code", -2);
			re.put("message", "任务已经停止不能继续提交考勤了");
			return re;
		}
		if(StringUtils.isBlank(roomDetail)){
			re.put("code", -2);
			re.put("message", "房型信息没提交");
			return re;
		}
		if(roomcount == null){//没有给房量
			roomcount = 0f;
		}
		HotelHmanager hhm = null;
		Hotelmanager hm = null;
		String pushkey = "";
		if(t.getPublisher() != null){
			List<HotelHmanager> hmli= hhmService.getBindHotelManager(t.getHotelid(), t.getPublisher(), 1);
			if(hmli.size() == 1){
				hhm = hmli.get(0);
			}else{
				hmli= hhmService.getBindHotelManager(t.getHotelid(), null, 1);
				if(hmli.size() > 0){
					hhm = hmli.get(0);
				}
			}
			if(hhm != null){
				hm = hotelmanagerService.findByUserid(hhm.getHmuserid());
				pushkey = hm.getPushkey();
			}
		}
		if(ctli.size() == 0){
			//还未创建考勤
			Childtask childtask = new Childtask();
			childtask.setAuditor(null);
			childtask.setCreattime(DateUtil.parseYMD(date));
			childtask.setEmid(userid);
			childtask.setRemark("帮工自己创建考勤");
			childtask.setResult(Constant.ATTENDANCE_SUBMIMT);
			childtask.setRoomcount(roomcount);
			childtask.setTaskid(taskid);
			childtask.setReward(0f);
			childTaskDao.save(childtask);
			ctli.add(childtask);
		}
		for(Childtask ct:ctli){
			if(DateUtil.formatYMD(ct.getCreattime()).equals(date)){
				Childtask childtask = ct;
				//酒店已经确认过了不能再修改
				if(ct.getResult().intValue() == Constant.ATTENDANCE_HASAUTH){
					re.put("code", -1);
					re.put("message", "考勤酒店已经确认过了不能再修改");
					return re;
				}
				//实际清理房量小于最低房量按照最低房量结算
				/*if(roomcount.intValue()<t.getLowestroom().intValue()){
					roomcount = t.getLowestroom();
				}*/
				childtask.setResult(Constant.ATTENDANCE_SUBMIMT);
				
				//先把历史纪录中的房型考勤删除
				String sql = "delete from tb_ct_roomtype where ctid="+ct.getId();
				entityManage.deleteByHql(sql);
				
				JSONArray roomArray = JSONObject.parseArray(roomDetail);//解析打扫房间详情
				float reward = 0f;
				float costmoney = 0f;
				for(Object o : roomArray){
					JSONObject roomJs = JSONObject.parseObject(o.toString());
					int id = roomJs.getIntValue("id");
					if(id>0){
						String count = roomJs.getString("count");
						HotelRoom room = hotelRoomService.getHoteRoomById(id);
						CtRoomtype ctRoom = new CtRoomtype();
						ctRoom.setCount(Float.valueOf(count));
						ctRoom.setCreatdate(new Date());
						ctRoom.setCtid(childtask.getId());
						ctRoom.setEmid(childtask.getEmid());
						ctRoom.setEmprice(room.getEmprice());
						ctRoom.setPrice(room.getHotelprice());
						ctRoom.setRoomname(room.getName());
						ctRoom.setRoomtypeid(room.getId());
						ctRoom.setTaskid(childtask.getTaskid());
						float emprice = 0f;
						float hprice = 0f;
						if(Constant.holidayMap.get(date) != null){//判断是否为节假日
							emprice = room.getHolidayeprice() == null?room.getEmprice():room.getHolidayeprice();
							hprice = room.getHolidayhprice() == null?room.getHotelprice():room.getHolidayhprice();
						}else{
							emprice = room.getEmprice();
							hprice = room.getHotelprice();
						}
						reward += emprice*Float.parseFloat(count);
						costmoney += hprice*Float.parseFloat(count);
						roomcount += Float.parseFloat(count);
						//保存房型信息
						entityManage.save(ctRoom);
					}
				}
				ct.setRoomcount(roomcount);//设置房间数量
				ct.setReward(reward);//帮工收入
				ct.setCostmoney(costmoney);//酒店花费
				childTaskDao.update(ct);
				if(!StrUtil.isNullOrEmpty(pushkey)){
					JSONObject reqparam = new JSONObject();
					reqparam.put("taskId", taskid);
					AppHotelPushUtil.pushMessage(hm.getPushkey(), 
					"【有人有活】", hm.getRealname()+"您好，帮工"+emName
					+ "已提交今日房量，请登录【有人有活App】查看详情。", "pageOrderDetail", reqparam);
			
				}
				
			}
		}
		re.put("code", 0);
		re.put("message", "考勤提交成功");
		return re;
	}

	@Override
	public Childtask getTaskAttendance(String taskid, String date, String emid) {
		return childTaskDao.getTaskAttendance(taskid, date, emid);
	}

	@Override
	public Map<String, Object> paymentChildTaskToEm(String taskid,
			Integer hotelid, String userid, Integer constraint, String realname) {
		Map<String,Object> data = new HashMap<String, Object>();
		Wallet expwallet = walletDao.getMyWallet(Constant.WALLET_ID.toString());
		Task t = taskDao.findTaskByTaskid(taskid);
		if(t.getState().intValue() != Constant.TASK_STATE_HASSERVICE.intValue()
				&& t.getState().intValue() != Constant.TASK_STATE_STOP.intValue()){
			data.put("code", -1);
			data.put("message", "订单状态不正确");
			return data;
		}
		//已确认的考勤
		List<Childtask>  ctli = new ArrayList<Childtask>();
		float costmoney = 0;
		
		List<Childtask>  li = childTaskDao.getAllEmTaskAttendance(taskid, null);
		Map<String, List<Childtask>> emct = new HashMap<String, List<Childtask>>();
		
		for(Childtask ct : li){
			if(ct.getResult().intValue() ==  Constant.ATTENDANCE_NO_SUBMIMT
					|| ct.getResult().intValue() ==  Constant.ATTENDANCE_SUBMIMT){
				if(constraint != null && constraint.intValue() == 1){//强制取消
					continue;
				}else{
					data.put("code", -2);
					data.put("message", "抱歉，该任务中有待确认考勤，请先进行确认操作后才确认完成。");
					return data;
				}
			}
			if(ct.getResult().intValue() == Constant.ATTENDANCE_HASAUTH){
				costmoney = costmoney+ct.getReward();
				ctli.add(ct);
				List<Childtask> list = emct.get(ct.getEmid());
				if(list == null){
					list = new ArrayList<Childtask>();
				}
				list.add(ct);
				emct.put(ct.getEmid(), list);
			}
		}
		
		if((expwallet.getBalance().floatValue()+expwallet.getOverdraft().floatValue())<costmoney){
			data.put("code", -3);
			data.put("message", "余额不足，不能支付");
			return data;
		}
		for(Childtask ct : ctli){
			//转账到帮工钱包
			ct = childTaskDao.findById(ct.getId());
			Wallet inwallet = walletDao.getMyWallet(ct.getEmid());
			String remark = "任务交易，任务id="+ct.getTaskid();
			Hotelmanager hm = hotelmanagerService.findByUserid(userid);
			if(ct.getReward() > 0){//创建流水记录
				billService.creatBill(expwallet.getId(), inwallet.getId(), ct.getReward(), 
					Constant.BILL_TYPE_TASK, remark, 
					ct.getTaskid(), ct.getId(), Constant.CHARGE_CHANNEL_TRANSFER,realname);
			}
			
			ct.setResult(Constant.ATTENDANCE_END);//状态修改为已确认
			ct.setAuditor(userid);
			childTaskDao.update(ct);
		}
		Iterator<Entry<String, List<Childtask>>> its = emct.entrySet().iterator();
		while (its.hasNext()) {
			Entry<String, List<Childtask>> en = its.next();
			String emid = en.getKey();
			Employee em = employeeDao.findEmployeeByUerid(emid);
			List<Childtask> ctlist = en.getValue();
			float money = 0;
			for(Childtask ct : ctlist){
				money = money + ct.getReward();
			}
			//是被终止的订单
			if(t.getState().intValue() == Constant.TASK_STATE_STOP.intValue()){
				if(!StrUtil.isNullOrEmpty(em.getPushkey())){
					DecimalFormat    df   = new DecimalFormat("######0.00"); 
					AppEmployyePushUtil.pushMessage(em.getPushkey(), 
							"【有人有活】", "您的任务"+t.getTaskid()
							+"已截止，收入金额¥"+df.format(money), "pageMyMoneyBag", null);
				}
				try {
					MsgHelp.sendHotelStopTask(em.getTel(), em.getRealname(), taskid, money);
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}else{
				if(!StrUtil.isNullOrEmpty(em.getPushkey())){
					DecimalFormat    df   = new DecimalFormat("######0.00"); 
					AppEmployyePushUtil.pushMessage(em.getPushkey(), 
							"【有人有活】", "您的任务"+t.getTaskid()
							+"已完成，收入金额¥"+df.format(money), "pageMyMoneyBag", null);
				}
				try {
					//发送短信通知帮工
					MsgHelp.sendHotelFinishTask(em.getTel(), em.getRealname(), taskid, money);
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}
		}
		if(t.getState().intValue() != Constant.TASK_STATE_STOP){
			//设置状态为已完成
			t.setState(Constant.TASK_STATE_END);
			taskDao.update(t);
		}
		data.put("code", 0);
		data.put("message", "任务确认成功");
		return data;
	}

	@Override
	public float getEmRoom(String userid) {
		String sql = "select sum(roomcount) from tb_child_task where emid='"+userid+"'";
		List<Object> re = entityManage.findBySql(sql);
		
		return re.get(0)==null?0:(Float.parseFloat(re.get(0).toString()));
	}

	@Override
	public Childtask findChildTaskById(Integer id) {
		return childTaskDao.findById(id);
	}

	@Override
	public void update(Childtask c) {
		childTaskDao.update(c);
	}

	@Override
	public List<Childtask> getEmChildTaskDetail(String taskId, String date) {
		List<Childtask> ctli = getTaskAttendance(taskId, date);
		for(Childtask ct : ctli){
			String sql2 = "SELECT roomtypeid, roomname, SUM(count),creatdate FROM tb_ct_roomtype "
					+ " WHERE taskid='"+taskId+"' AND creatdate='"+date+"' AND emid='"+ct.getEmid()+"'"
					+ " GROUP BY roomtypeid,roomname, creatdate";
			List<Object> ctLi = entityManage.findBySql(sql2);
			JSONArray array = new JSONArray();
			for(int i= 0 ; i<ctLi.size(); i++){
				Map<String, Object> roomType = new HashMap<String, Object>();
				Object[] ory = (Object[]) ctLi.get(i);
				if(ory[0] != null){//房型ID
					roomType.put("id", ory[0].toString());
				}
				if(ory[1] != null){//房型名ID
					roomType.put("name", ory[1].toString());
				}
				if(ory[2] != null){//数量ID
					roomType.put("count", ory[2].toString());
				}
				if(ory[3] != null){//时间
					roomType.put("date", ory[3].toString());
				}
				array.add(roomType);
			}
			ct.setRoomdetail(array);
		}
		return ctli;
	}

	@Override
	public Map<String, Object> editTaskAttendance(Integer ctId, String roomDetail) {
		Map<String, Object> re = new HashMap<String, Object>();
		Childtask ct = findChildTaskById(ctId);
		//酒店已经确认过了不能再修改
		if(ct.getResult().intValue() == Constant.ATTENDANCE_HASAUTH){
			re.put("code", -1);
			re.put("message", "考勤酒店已经确认过了不能再修改");
			return re;
		}
		//实际清理房量小于最低房量按照最低房量结算
		/*if(roomcount.intValue()<t.getLowestroom().intValue()){
			roomcount = t.getLowestroom();
		}*/
		ct.setResult(Constant.ATTENDANCE_SUBMIMT);
		
		//先把历史纪录中的房型考勤删除
		String sql = "delete from tb_ct_roomtype where ctid="+ct.getId();
		entityManage.deleteByHql(sql);
		
		JSONArray roomArray = JSONObject.parseArray(roomDetail);//解析打扫房间详情
		float reward = 0f;
		float costmoney = 0f;
		float roomcount = 0f;
		for(Object o : roomArray){
			JSONObject roomJs = JSONObject.parseObject(o.toString());
			int id = roomJs.getIntValue("id");
			if(id>0){
				String count = roomJs.getString("count");
				HotelRoom room = hotelRoomService.getHoteRoomById(id);
				CtRoomtype ctRoom = new CtRoomtype();
				ctRoom.setCount(Float.valueOf(count));
				ctRoom.setCreatdate(new Date());
				ctRoom.setCtid(ct.getId());
				ctRoom.setEmid(ct.getEmid());
				ctRoom.setEmprice(room.getEmprice());
				ctRoom.setPrice(room.getHotelprice());
				ctRoom.setRoomname(room.getName());
				ctRoom.setRoomtypeid(room.getId());
				ctRoom.setTaskid(ct.getTaskid());
				float emprice = 0f;
				float hprice = 0f;
				if(Constant.holidayMap.get(DateUtil.formatYMD(ct.getCreattime())) != null){//判断是否为节假日
					emprice = room.getHolidayeprice() == null?room.getEmprice():room.getHolidayeprice();
					hprice = room.getHolidayhprice() == null?room.getHotelprice():room.getHolidayhprice();
				}else{
					emprice = room.getEmprice();
					hprice = room.getHotelprice();
				}
				reward += emprice*Float.parseFloat(count);
				costmoney += hprice*Float.parseFloat(count);
				roomcount += Float.parseFloat(count);
				//保存房型信息
				entityManage.save(ctRoom);
			}
		}
		ct.setRoomcount(roomcount);//设置房间数量
		ct.setReward(reward);//帮工收入
		ct.setCostmoney(costmoney);//酒店花费
		childTaskDao.update(ct);
		re.put("code", 0);
		re.put("message", "修改成功");
		return re;
	}
}
